import React, { useEffect, useRef } from 'react';
import { useAuthStore } from '../stores/authStore';
import { Spin } from 'antd';

interface AuthProviderProps {
  children: React.ReactNode;
}

const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const { isLoading, initializeAuth } = useAuthStore();
  const hasInitialized = useRef(false);
  const initPromise = useRef<Promise<void> | null>(null);

  useEffect(() => {
    // 根据项目规范：应用启动时必须调用认证初始化方法
    const initialize = async () => {
      if (!hasInitialized.current && !initPromise.current) {
        console.log('AuthProvider: 开始初始化认证状态');
        hasInitialized.current = true;
        try {
          initPromise.current = initializeAuth();
          await initPromise.current;
          console.log('AuthProvider: 认证状态初始化完成');
        } catch (error) {
          console.error('AuthProvider: 认证状态初始化失败', error);
          // 即使初始化失败，也标记为已初始化，避免无限重试
          hasInitialized.current = true;
        } finally {
          initPromise.current = null;
        }
      }
    };

    initialize();
  }, [initializeAuth]);

  // 在认证状态初始化期间显示加载状态
  if (isLoading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        backgroundColor: '#000',
        flexDirection: 'column',
        gap: '16px'
      }}>
        <Spin size="large" />
        <div style={{ color: '#fff', fontSize: '16px' }}>初始化中...</div>
      </div>
    );
  }

  return <>{children}</>;
};

export default AuthProvider;